package cn.edu.lzzy.mypractices.web.chapter;

import cn.edu.lzzy.mypractices.constant.ApiConstant;
import cn.edu.lzzy.mypractices.constant.Messages;
import cn.edu.lzzy.mypractices.entity.Chapter;
import cn.edu.lzzy.mypractices.entity.Course;
import cn.edu.lzzy.mypractices.service.ChapterService;
import cn.edu.lzzy.mypractices.service.CourseService;
import cn.edu.lzzy.mypractices.util.StringUtils;
import cn.edu.lzzy.mypractices.web.model.ApiResult;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Api(tags = "课程章节业务")
@CrossOrigin
@RestController
@RequestMapping(ApiConstant.ROUTE_CHAPTER_ROOT)
public class ChapterApiController {
    private final ChapterService chapterService;
    private final CourseService courseService;

    public ChapterApiController(ChapterService chapterService, CourseService courseService) {
        this.chapterService = chapterService;
        this.courseService = courseService;
    }

    @ApiOperation("查询课程的所有章节")
    @GetMapping(ApiConstant.ROUTE_CHAPTER_TEACHER)
    public ApiResult getAllChaptersByCourse(@RequestParam String token, @RequestParam UUID courseId) {
        List<ApiResult.VmChapter> chapterList = new ArrayList<>();
        chapterService.getByCourse(courseId).forEach(o -> chapterList.add(ApiResult.VmChapter.create(o)));
        return new ApiResult(true, chapterService.count(courseId) + "", chapterList);
    }

    @ApiOperation("查询开放章节(学生)")
    @GetMapping(ApiConstant.ROUTE_CHAPTER_STUDENT)
    public ApiResult getOpenedChaptersByCourse(@RequestParam String token, @RequestParam UUID courseId) {
        List<ApiResult.VmChapter> chapters = new ArrayList<>();

        chapterService.getByCourse(courseId).forEach(chapter -> {
            if (chapter.isOpen()) {
                chapters.add(ApiResult.VmChapter.create(chapter));
            }
        });

        return new ApiResult(true, chapterService.count(courseId) + "", chapters);
    }

    private ApiResult addOrUpdate(String courseId, String chapterId, JSONObject json, boolean isUpdate) {
        String token = json.getString(ApiConstant.KEY_TOKEN);

        String name = json.getString(ApiConstant.KEY_CHAPTER_NAME);
        String desc = json.getString(ApiConstant.KEY_CHAPTER_DESCRIPTION);
        boolean open = json.getBoolean(ApiConstant.KEY_CHAPTER_OPEN);

        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(desc) || StringUtils.isEmpty(courseId) || (isUpdate && chapterId == null)) {
            return new ApiResult(false, Messages.INCOMPLETE_INFO.toString(), null);
        }

        // 查询课程列表检查是否有该课程
        Course course = courseService.getById(UUID.fromString(courseId));
        if (course == null) {
            return new ApiResult(false, Messages.WRONG_ID.toString(), null);
        }

        Chapter chapter;
        boolean create = chapterId == null;
        if (create) {
            chapter = new Chapter();
            chapter.setCourse(course);
        } else {
            //根据id获取数据库的指定章节
            chapter = chapterService.getByChapterId(UUID.fromString(chapterId));
            if (chapter == null) {
                return new ApiResult(false, Messages.WRONG_ID.toString(), null);
            }
        }

        chapter.setName(name);
        chapter.setDescription(desc);
        chapter.setOpen(open);

        if (create) {
            Chapter created = chapterService.add(chapter);
            return new ApiResult(true, "", ApiResult.VmChapter.create(created));
        } else {
            chapter.setUpdateTime(new Date());
            Chapter updated = chapterService.update(chapter, token);
            if (updated == null) {
                return new ApiResult(false, Messages.NO_PERMISSION.toString(), null);
            }
            return new ApiResult(true, "", ApiResult.VmChapter.create(updated));
        }
    }

    // 得提供courseId
    @ApiOperation("新增章节")
    @PostMapping(value = ApiConstant.ROUTE_CHAPTER_ADD, produces = ApiConstant.API_PRODUCES)
    public ApiResult addChapter(@RequestParam(value = "course") String courseId, @RequestBody JSONObject chapter) {
        return addOrUpdate(courseId, null, chapter, false);
    }

    @ApiOperation("更新指定章节")
    @PostMapping(value = ApiConstant.ROUTE_CHAPTER_PUT, produces = ApiConstant.API_PRODUCES)
    public ApiResult updateChapter(@RequestParam(value = "course") String courseId, @RequestParam(value = "chapter") String chapterId, @RequestBody JSONObject chapter) {
        return addOrUpdate(courseId, chapterId, chapter, true);
    }

    @ApiOperation("删除章节")
    @DeleteMapping(value = ApiConstant.ROUTE_CHAPTER_DELETE, produces = ApiConstant.API_PRODUCES)
    public ApiResult deleteChapter(@RequestBody JSONObject json) {
        String token = json.getString(ApiConstant.KEY_TOKEN);
        String chapterId = json.getString(ApiConstant.KEY_CHAPTER_ID);
        if (StringUtils.isEmpty(token) && StringUtils.isEmpty(chapterId)) {
            return new ApiResult(false, Messages.INCOMPLETE_INFO.toString(), null);
        }

        try {
            UUID courseId = UUID.fromString(chapterId);
            Messages msg = chapterService.remove(courseId, token);
            return new ApiResult(msg == Messages.SUCCESS, msg.toString(), null);
        } catch (Exception e) {
            return new ApiResult(false, Messages.WRONG_ID.toString(), e.getMessage());
        }
    }
}
